window.themePath = "/user/theme/default/";

jQuery.cachedScript = function (url, options) {
    options = $.extend(options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });
    return jQuery.ajax(options);
};

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(Y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

$(document).ready(function () {
    doMarkDownRender();
    doCommentView();
    doLinkApply();
});

function doMarkDownRender() {
    var needPretty = true;
    var canPretty = false;
    $(".markdown").each(function (i, item) {
        var $i = $(item);
        var markedString = marked($i.html().replace("[break]", ""));
        $i.html(markedString);
        if (markedString.indexOf("</pre>") >= 1 && needPretty) {
            needPretty = false;
            $("<link>").attr({"type": "text/css", "rel": "stylesheet", "href": window.themePath + "js/prettify/prettify.css"}).appendTo("head");
            $.cachedScript(window.themePath + "js/prettify/prettify.js").done(function () {
                canPretty = true;
            });
        }
    });
    if (!needPretty) {
        var interval = setInterval(function () {
            console.log("check pretty");
            if (canPretty) {
                $('.markdown pre').addClass("prettyprint").addClass("linenums");
                prettyPrint();
                clearInterval(interval);
            }
        }, 100);
    }
}

function doCommentView() {
    var $form = $('#comment-form');
    var status = $('.article-one').data("status");
    if (!status) {
        $form.remove();
        return;
    }
    var id = $('.article-one').attr("id").toString().replace("article-", "");
    ajaxCommentLoad(id);
    var $archived = $('#comment-archived');
    if (status != "published") {
        $form.remove();
        $archived.show();
        return;
    }
    $form.show();
    $archived.remove();
    ajaxComment(id, $form);
}

function ajaxComment(id, $form) {
    if (!id) {
        $form.find(".btn").remove();
        return;
    }
    var url = "/article/comment/" + id + "/";
    var $author = $('#comment-author').val(localStorage.getItem("comment_author"));
    var $email = $('#comment-email').val(localStorage.getItem("comment_email"));
    var $url = $('#comment-url').val(localStorage.getItem("comment_url"));
    var $comment = $('#comment');
    var $submit = $("comment-submit");
    $.cachedScript(window.themePath + "js/jquery.form.js").done(function () {
        $form.ajaxForm({
            url: url,
            dataType: "json",
            beforeSubmit: function () {
                $submit.hide(100);
            },
            success: function (json) {
                localStorage.setItem("comment_author", $author.val());
                localStorage.setItem("comment_email", $email.val());
                localStorage.setItem("comment_url", $url.val());
                if (json.res) {
                    $('#comment-content').val("");
                    var time = new Date(json.comment.add_time * 1000);
                    json.comment.add_time = time.Format("MM.dd hh:mm");
                    var $html = $(template("comment-tpl", json.comment));
                    if (json.comment.status != "approved") {
                        $html.find(".comment-meta-header").append('<span class="comment-pending">评论审核中...</span>');
                    }
                    $html.find(".comment-reply").remove();
                    $html.find(".comment-meta-header").append('<span class="comment-new">(new)</span>');
                    $comment.append($html);
                    $(".replying").trigger("click");
                    $("body").animate({
                        scrollTop: $form.offset().top
                    }, 500);
                    var $author = $(".comment-author");
                    if ($author.attr("href") != "#") {
                        $author.attr("target", "_blank");
                    }
                }
                $submit.show(100);
            }
        })
    });
    $comment.on("click", ".comment-reply", function () {
        var $this = $(this);
        var id = $this.attr("href");
        var $parent = $('#comment-parent');
        if ($this.hasClass("replying")) {
            $('#comment').after($form.detach());
            $(this).removeClass("replying").text("回复");
            $parent.val(0);
            return false;
        }
        $('.replying').trigger("click");
        $(id).find(".comment-content").eq(0).after($form.detach());
        $parent.val(id.toString().replace("#comment-", ""));
        $this.addClass("replying").text("取消回复");
        return false;
    });
}

function ajaxCommentLoad(id) {
    var url = "/article/comment/" + id + "/";
    $.get(url, function (json) {
        json = JSON.parse(json);
        var maxIndex = 0;
        if (json.comment.length < 1) {
            return;
        }
        var tpl = template($('#comment-tpl').html());
        var tmpComments = {};
        var topComments = [];
        var $comment = $('#comment');
        $(json.comment.reverse()).each(function (i, item) {
            var time = new Date(item.add_time * 1000);
            item.add_time = time.Format("MM.dd hh:mm");
            var $html = $(tpl(item));
            if (item.status == "pending") {
                $html.find(".comment-reply").before('<span class="comment-pending">评论审核中...</span>');
            }
            var key1 = "comment-" + item.id;
            var key2 = "comment-" + item.parent_id;
            if (tmpComments[key1]) {
                $(tmpComments[key1].reverse()).each(function (i, item) {
                    $html.find("> .comment-container").append(item);
                });
            }
            if (item.parent_id > 0) {
                if (!tmpComments[key2]) {
                    tmpComments[key2] = [];
                }
                $html.addClass("comment-child");
                tmpComments[key2].push($html);
            } else {
                topComments.push($html);
            }
        });
        $(topComments.reverse()).each(function (i, item) {
            var index = parseInt(i / 6);
            item.addClass("comment-index-" + index);
            maxIndex = index;
            $comment.append(item);
        });
        var $author = $(".comment-author");
        if ($author.attr("href") != "#") {
            $author.attr("target", "_blank");
        }
        if (maxIndex > 0) {
            var $header = $(".comment-header");
            for (var i = 0; i <= maxIndex; i++) {
                $header.append('<a class="item index-' + i + '" href="#index-' + i + '">' + (i + 1) + "</a>");
            }
            $('.index-' + maxIndex).addClass("active");
            $('.comment-item').hide();
            $('.comment-index-' + maxIndex).show();
        }
        $(".comment-header").on("click", ".item", function () {
            var $this = $(this);
            if ($this.hasClass("active")) {
                return false;
            }
            $('.item.active').removeClass("active");
            $(this).addClass("active");
            $comment.find(">.comment-item").hide();
            var tabIndex = $this.attr("href").toString().replace("#", ".comment-");
            $comment.find(tabIndex).show();
            return false;
        })
    });
}

function doLinkApply() {
    var $form = $("#link-apply-form");
    if ($form.length < 1) {
        return;
    }
    $form.ajaxForm({
        dataType: "json",
        error: function () {
            alert("系统错误");
        },
        success: function (json) {
            if (json.res) {
                alert("已经记录你的申请，等待审核");
                return;
            }
            if (json.msg) {
                alert(json.msg);
            }
        }
    });
}